package com.java.demo.sync;

import java.util.concurrent.locks.ReentrantLock;

public class FairAndNoFairLock implements Runnable{
    private int seats = 1000;

//    private ReentrantLock lock = new ReentrantLock();  // 默认非公平锁
    private ReentrantLock lock = new ReentrantLock(true);  // 使用公平锁

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (seats > 0) {
                    seats -= 1;
                    System.out.println(Thread.currentThread().getName() + ", seats=" + seats);
                } else {
                    System.out.println(Thread.currentThread().getName() + ", seats=" + seats);
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        FairAndNoFairLock main = new FairAndNoFairLock();
        Thread t1 = new Thread(main, "A");
        Thread t2 = new Thread(main, "B");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
